﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;

namespace ProjectManageSystemApi.Services.Impl
{
    public class UploadServices : IUploadServices
    {
        readonly Config _config;
        readonly ILogger<UploadServices> _logger;
        public UploadServices(Config config, ILogger<UploadServices> logger)
        {
            _config = config;
            _logger = logger;
        }

        /// <summary>
        /// 保存考勤照片
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool UserCheckInfoUpload(IFormFile file, out string filePath) 
        {
            string suffix = Path.GetExtension(file.FileName);
            string subFolder = DateTime.Now.ToString("yyyy-MM");
            string name = Guid.NewGuid().ToString("N");
            string fileName = name + suffix;
            string minFileName = name + "_min" + suffix;
            string subPath = Path.Combine(_config.PublicPath, _config.UserCheckInfoUploadPath, subFolder);
            if (!Directory.Exists(subPath)) 
            {
                Directory.CreateDirectory(subPath);
            }

            string path = Path.Combine(subPath, fileName);
            string minPath = Path.Combine(subPath, minFileName);
            filePath = subFolder + "/" + fileName;
            return UploadSaveAsync(file, path).Result && UploadSaveMiniAysnc(file, minPath).Result;
        }

        /// <summary>
        /// 报销图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool CostInfoUpload(IFormFile file, out string filePath)
        {
            string suffix = Path.GetExtension(file.FileName);
            string subFolder = DateTime.Now.ToString("yyyy-MM");
            string name = Guid.NewGuid().ToString("N");
            string fileName = name + suffix;
            string minFileName = name + "_min" + suffix;
            string subPath = Path.Combine(_config.PublicPath, _config.CostInfoUploadPath, subFolder);
            if (!Directory.Exists(subPath))
            {
                Directory.CreateDirectory(subPath);
            }

            string path = Path.Combine(subPath, fileName);
            string minPath = Path.Combine(subPath, minFileName);
            filePath = subFolder + "/" + fileName;
            return UploadSaveAsync(file, path).Result && UploadSaveMiniAysnc(file, minPath).Result;
        }

        /// <summary>
        /// 工程项目图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool ProjectItemInfoUpload(IFormFile file, out string filePath)
        {
            string suffix = Path.GetExtension(file.FileName);
            string subFolder = DateTime.Now.ToString("yyyy-MM");
            string name = Guid.NewGuid().ToString("N");
            string fileName = name + suffix;
            string minFileName = name + "_min" + suffix;
            string subPath = Path.Combine(_config.PublicPath, _config.ProjectItemInfoUploadPath, subFolder);
            if (!Directory.Exists(subPath))
            {
                Directory.CreateDirectory(subPath);
            }

            string path = Path.Combine(subPath, fileName);
            string minPath = Path.Combine(subPath, minFileName);
            filePath = subFolder + "/" + fileName;
            return UploadSaveAsync(file, path).Result && UploadSaveMiniAysnc(file, minPath).Result;
        }

        /// <summary>
        /// 工程单据图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool ProjectBillInfoUpload(IFormFile file, out string filePath)
        {
            string suffix = Path.GetExtension(file.FileName);
            string subFolder = DateTime.Now.ToString("yyyy-MM");
            string name = Guid.NewGuid().ToString("N");
            string fileName = name + suffix;
            string minFileName = name + "_min" + suffix;
            string subPath = Path.Combine(_config.PublicPath, _config.ProjectBillInfoUploadPath, subFolder);
            if (!Directory.Exists(subPath))
            {
                Directory.CreateDirectory(subPath);
            }

            string path = Path.Combine(subPath, fileName);
            string minPath = Path.Combine(subPath, minFileName);
            filePath = subFolder + "/" + fileName;
            return UploadSaveAsync(file, path).Result && UploadSaveMiniAysnc(file, minPath).Result;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private async Task<bool> UploadSaveAsync(IFormFile file, string filePath) 
        {
            try
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                return true;
            }
            catch (Exception e)
            {
                _logger.LogWarning("保存图片失败：" + e.ToString());
                return false;
            }
        }

        /// <summary>
        /// 保存缩略图
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private async Task<bool> UploadSaveMiniAysnc(IFormFile file, string filePath) 
        {
            if (file.Length < 102400)  // 小于100k的图片，就不用压缩了吧
            {
                return await UploadSaveAsync(file, filePath);
            }
            try
            {
                using(var stream = file.OpenReadStream())
                using (Bitmap bitmap = new Bitmap(stream, false))
                {
                    int width = 200;
                    int height = (int)(bitmap.Height * (200.0d / bitmap.Width));
                    Bitmap newImage = new Bitmap(width, height);
                    Graphics g = Graphics.FromImage(newImage);
                    g.DrawImage(bitmap, 0, 0, width, height);
                    g.Dispose();
                    newImage.Save(filePath);
                    return true;
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning("保存压缩图片失败：" + e.ToString());
                return false;
            }
        }

        /// <summary>
        /// app上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool AppUpload(IFormFile file, out string filePath)
        {
            string suffix = Path.GetExtension(file.FileName);
            string name = Guid.NewGuid().ToString("N");
            string fileName = name + suffix;
            string subPath = Path.Combine(_config.PublicPath, _config.AppInfoPath);
            if (!Directory.Exists(subPath))
            {
                Directory.CreateDirectory(subPath);
            }

            string path = Path.Combine(subPath, fileName);
            filePath = "/" + fileName;
            return UploadSaveAsync(file, path).Result;
        }
    }
}
